//
//  MapPOIViewController.m
//  Runner
//
//  Created by mac on 2021/12/1.
//

#import "MapPOIViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "POITableViewCell.h"

/** 设备的宽 */
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
/** 设备的高 */
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
@interface MapPOIViewController ()<UISearchControllerDelegate,UISearchResultsUpdating,MAMapViewDelegate,AMapLocationManagerDelegate,AMapSearchDelegate,UITableViewDelegate,UITableViewDataSource>


@property (nonatomic, strong)UISearchController *searchController;//搜索框
@property (nonatomic, assign)CLLocationCoordinate2D currentLocationCoordinate;//当前位置的经纬度
@property (nonatomic, strong)MAMapView * mapView;//地图
@property (nonatomic, strong)AMapLocationManager *locationManager;
@property (nonatomic, strong)UITableView *tableView;//展示 poi 数据 和 搜索的地点
@property (nonatomic,strong)AMapSearchAPI *mapSearch;//poi 搜索
@property (nonatomic,strong)NSArray *dataArray;//poi 搜索的数据源
@property (nonatomic ,strong)AMapPOIAroundSearchRequest *request; //周边 搜索
@property (nonatomic ,strong)AMapPOIKeywordsSearchRequest *keywordsRequest;//关键字 搜索
@property (nonatomic ,strong)NSIndexPath *selectedIndexPath;//poi选择的第几个
@property (nonatomic ,strong)UITableView *searchTableView;//用于搜索的tableView
@property (nonatomic ,strong)NSArray *tipsArray;//搜索提示的数组
@property (nonatomic, assign) bool isKeywordSearch;//是否是 关键字搜索 默认 No

@property (nonatomic ,strong) NSMutableDictionary *resultDic; // 选择的地理位置信息


@end

@implementation MapPOIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19], NSForegroundColorAttributeName:UIColorFromRGB(0x1296db)}];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"avcBackIcon"] style:UIBarButtonItemStylePlain target:self action:@selector(onClickClose:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(done)];
    [UINavigationBar appearance].barTintColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    

    self.title = @"定位";
    [self setUpSearchController];

    if (@available(iOS 13.0, *)) {
        self.view.backgroundColor = [UIColor systemGroupedBackgroundColor];
       } else {
           // Fallback on earlier versions
           self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
       }

    [self initMapView];
    [self.view addSubview:self.tableView];
    [self configLocationManager];


    self.mapSearch = [[AMapSearchAPI alloc] init];
    self.mapSearch.delegate = self;


// 关键字 搜索
    self.keywordsRequest = [[AMapPOIKeywordsSearchRequest alloc]init];
    self.keywordsRequest.keywords = self.address;//@"商务住宅|餐饮服务|生活服务";
//    self.keywordsRequest.requireExtension    = YES;
//    self.keywordsRequest.cityLimit           = YES;
//    self.keywordsRequest.requireSubPOIs      = YES;

    if (!kStringIsEmpty(self.address)) {//文字 搜索

        self.isKeywordSearch = YES;
        //关键字搜索
        [self kPOIKeywordsSearchRequest];
    }else{//定位 搜索
        self.isKeywordSearch = NO;
        [self locateAction];
    }

    self.request = [[AMapPOIAroundSearchRequest alloc] init];
    self.request.keywords  = @"商务住宅|餐饮服务|生活服务";
    /* 按照距离排序. */
    self.request.sortrule = 0;
//    self.request.offset = 50;
//    self.request.requireExtension = YES;


    self.selectedIndexPath=[NSIndexPath indexPathForRow:-1 inSection:-1];
}

- (void)done {
    if (!kDictIsEmpty(self.resultDic)) {
        if ([self.delegate respondsToSelector:@selector(mapPOIViewDelgate:)]) {
            [self.delegate mapPOIViewDelgate:self.resultDic];
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)onClickClose:(UIButton *)btn
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 关键字 搜索
- (void)kPOIKeywordsSearchRequest{

    [self.mapSearch AMapPOIKeywordsSearch:self.keywordsRequest];
}

// 周边 搜索
- (void)kPOIAroundSearchRequest{

    [self.mapSearch AMapPOIAroundSearch:self.request];
}

- (void)setUpSearchController{
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.delegate = self;
    self.searchController.searchResultsUpdater = self;
    self.searchController.hidesNavigationBarDuringPresentation = NO;


    if (@available(iOS 12.0, *)) {
        self.searchController.obscuresBackgroundDuringPresentation = NO;
    }else{
        self.searchController.dimsBackgroundDuringPresentation = NO;
    }

    UISearchBar *bar = self.searchController.searchBar;
    bar.frame = CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_WIDTH, 44);
    bar.barStyle = UIBarStyleDefault;
    bar.translucent = YES;


    if (@available(iOS 13.0, *)) {

        bar.barTintColor = [UIColor systemGroupedBackgroundColor];

    } else {
           // Fallback on earlier versions
           bar.barTintColor = [UIColor groupTableViewBackgroundColor];

        }

    bar.tintColor = [UIColor colorWithRed:0 green:(190 / 255.0) blue:(12 / 255.0) alpha:1];
    UIImageView *view = [[[bar.subviews objectAtIndex:0] subviews] firstObject];
    view.layer.borderColor = [UIColor colorWithRed:((0xdddddd >> 16) & 0x000000FF)/255.0f green:((0xdddddd >> 8) & 0x000000FF)/255.0f blue:((0xdddddd) & 0x000000FF)/255.0 alpha:1].CGColor;
    view.layer.borderWidth = 0.7;

    bar.showsBookmarkButton = NO;
    UITextField *searchField = [bar valueForKey:@"searchField"];
    searchField.placeholder = @"搜索地点";
    if (searchField) {
        [searchField setBackgroundColor:[UIColor whiteColor]];
        searchField.layer.cornerRadius = 3.0f;
        searchField.layer.borderColor = [UIColor colorWithRed:((0xdddddd >> 16) & 0x000000FF)/255.0f green:((0xdddddd >> 8) & 0x000000FF)/255.0f blue:((0xdddddd) & 0x000000FF)/255.0 alpha:1].CGColor;
        searchField.layer.borderWidth = 0.7;
    }

    [self.view addSubview:bar];
}

- (void)initMapView{
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 64 + 44, SCREEN_WIDTH, 300)];
    self.mapView.delegate = self;
    self.mapView.mapType = MAMapTypeStandard;
    self.mapView.showsScale = NO;
    self.mapView.showsCompass = NO;
    self.mapView.showsUserLocation = YES;
    self.mapView.zoomLevel = 15.0;
    [self.view addSubview:self.mapView];

    UIButton *localButton = [UIButton buttonWithType:UIButtonTypeCustom];
    localButton.backgroundColor = [UIColor redColor];
    localButton.frame = CGRectMake(SCREEN_WIDTH - 60, 240, 50, 50);
    [localButton addTarget:self action:@selector(localButtonAction) forControlEvents:UIControlEventTouchUpInside];
    localButton.layer.cornerRadius = 25;
    localButton.clipsToBounds = YES;
    [localButton setImage:[UIImage imageNamed:@"定位"] forState:UIControlStateNormal];
    [self.mapView addSubview:localButton];

}

- (UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 408, SCREEN_WIDTH, SCREEN_HEIGHT - 408) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];

    }
    return _tableView;
}

- (UITableView *)searchTableView{
    if (_searchTableView == nil) {
        _searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - GK_STATUSBAR_NAVBAR_HEIGHT) style:UITableViewStylePlain];
        _searchTableView.delegate = self;
        _searchTableView.dataSource = self;
        _searchTableView.tableFooterView = [UIView new];
    }
    return _searchTableView;
}

// 定位SDK
- (void)configLocationManager {
    self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //单次定位超时时间
    [self.locationManager setLocationTimeout:6];
    [self.locationManager setReGeocodeTimeout:3];
}

- (void)locateAction {

    [self.mapView removeAnnotations:self.mapView.annotations];
    //带逆地理的单次定位
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error) {
            NSLog(@"locError:{%ld - %@};",(long)error.code,error.localizedDescription);
            if (error.code == AMapLocationErrorLocateFailed) {
                return ;
            }
        }
        //定位信息
        NSLog(@"location:%@", location);
        if (regeocode)
        {
            self.currentLocationCoordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);

            [self showMapPoint];
            [self setCenterPoint];
            self.request.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];

            [self kPOIAroundSearchRequest];
        }
    }];

}

#pragma mark - 地图添加大头针
- (void)showMapPoint{
    if (self.mapView.annotations) {
        [self.mapView removeAnnotations:self.mapView.annotations];
    }
    MAPointAnnotation * centerAnnotation = [[MAPointAnnotation alloc] init];
    centerAnnotation.coordinate = self.currentLocationCoordinate;
    centerAnnotation.title = @"";
    centerAnnotation.subtitle = @"";
    [self.mapView addAnnotation:centerAnnotation];

}
#pragma mark - 把当前位置设置为地图的中心点
- (void)setCenterPoint{

    [_mapView setZoomLevel:15.0];
    [_mapView setCenterCoordinate:self.currentLocationCoordinate animated:YES];
}


#pragma mark - MAMapView Delegate
- (MAAnnotationView *)mapView:(MAMapView *)mapView
            viewForAnnotation:(id<MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {// 添加大头针
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        annotationView.pinColor = MAPinAnnotationColorRed;
        return annotationView;
    }
//    else
//        if ([annotation isKindOfClass:[MAUserLocation class]]) {// 自定义 当前定位点的图标
//        static NSString *userLocationStyleReuseIndetifier = @"userLocationStyleReuseIndetifier";
//        MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:userLocationStyleReuseIndetifier];
//        if (annotationView == nil) {
//            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:userLocationStyleReuseIndetifier];
//        }
//        annotationView.image = [UIImage imageNamed:@"icon_tracking_userLocation"];
//        return annotationView;
//    }
    return nil;
}

#pragma make - 点击地图
- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate;{

    self.currentLocationCoordinate = coordinate;
//        默认选择 第一个
        self.selectedIndexPath=[NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView setContentOffset:CGPointMake(0,0) animated:NO];

        self.request.location = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];


            [self showMapPoint];
            [self setCenterPoint];

        //周边搜索
        if (!self.isKeywordSearch) {//区分 定位 周边 还是 关键字 周边
            [self kPOIAroundSearchRequest];
        }


}


#pragma mark -AMapSearchDelegate
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    NSMutableArray *remoteArray = response.pois.mutableCopy;

        self.dataArray = remoteArray;

        if (self.dataArray.count>0) {

            self.selectedIndexPath=[NSIndexPath indexPathForRow:0 inSection:0];//默认第一个选中

            AMapPOI *POIModel = self.dataArray[0];
            // 获取得到的地理信息
            NSMutableDictionary *resultDic = [[NSMutableDictionary alloc]init];
            resultDic[@"province"] = POIModel.province;//省
            resultDic[@"city"] = POIModel.city;//市
            resultDic[@"ad"] = POIModel.district;//行政区
            resultDic[@"snippet"] = POIModel.address;//地址信息
            resultDic[@"title"] = POIModel.name;//名称
            resultDic[@"lng"] = [NSString stringWithFormat:@"%f",POIModel.location.longitude];//经度
            resultDic[@"lat"] = [NSString stringWithFormat:@"%f",POIModel.location.latitude];//纬度
            self.resultDic = resultDic;

            if (self.isKeywordSearch) {// 文字搜索 选择 第一个

                AMapPOI *POIModel = self.dataArray[0];
                CLLocationCoordinate2D locationCoordinate = CLLocationCoordinate2DMake(POIModel.location.latitude, POIModel.location.longitude);

                self.currentLocationCoordinate = locationCoordinate;

                [self showMapPoint];
                [self setCenterPoint];

                self.isKeywordSearch = NO;

            }
        }


    [self.tableView reloadData];

}

- (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response{

    self.tipsArray = response.tips;
    [self.searchTableView reloadData];

}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.tableView) {
        return self.dataArray.count;
    }else{
        return self.tipsArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"POITableViewCell";
    POITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:cellID owner:nil options:nil] firstObject];
    }
    if (tableView == self.tableView) {
        AMapPOI *POIModel = self.dataArray[indexPath.row];
        cell.nameLabel.text = POIModel.name;
        cell.addressLable.text = POIModel.address;

        if (indexPath.row==self.selectedIndexPath.row){
            NSLog(@"%ld",(long)indexPath.row);
            NSLog(@"%ld",(long)self.selectedIndexPath.row);

            cell.accessoryType=UITableViewCellAccessoryCheckmark;
        }else{
            cell.accessoryType=UITableViewCellAccessoryNone;
        }
    }else{
        AMapTip *tipModel = self.tipsArray[indexPath.row];
        cell.nameLabel.text = tipModel.name;
        cell.addressLable.text = tipModel.address;

    }

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


    if (self.tableView == tableView) {
        self.selectedIndexPath=indexPath;
        [tableView reloadData];
        AMapPOI *POIModel = self.dataArray[indexPath.row];
        CLLocationCoordinate2D locationCoordinate = CLLocationCoordinate2DMake(POIModel.location.latitude, POIModel.location.longitude);

        self.currentLocationCoordinate = locationCoordinate;
        [self showMapPoint];
        [self setCenterPoint];

        // 获取得到的地理信息
        NSMutableDictionary *resultDic = [[NSMutableDictionary alloc]init];
        resultDic[@"province"] = POIModel.province;//省
        resultDic[@"city"] = POIModel.city;//市
        resultDic[@"ad"] = POIModel.district;//行政区
        resultDic[@"snippet"] = POIModel.address;//地址信息
        resultDic[@"title"] = POIModel.name;//名称

        resultDic[@"lng"] = [NSString stringWithFormat:@"%f",POIModel.location.longitude];//经度
        resultDic[@"lat"] = [NSString stringWithFormat:@"%f",POIModel.location.latitude];//纬度
        self.resultDic = resultDic;

        NSLog(@"%@", resultDic);

    }else{

        //搜索
        self.searchController.active = NO;

        if (@available(iOS 13.0, *)) {
            UIWindow *window = nil;
            for (UIWindowScene *windowScene in [UIApplication sharedApplication].connectedScenes) {

                if (windowScene.activationState == UISceneActivationStateForegroundActive) {

                    window = windowScene.windows.firstObject;

                    break;

                }
            }
            [window endEditing:YES];
        } else {
            [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        }

        AMapTip *tipModel = self.tipsArray[indexPath.row];
        CLLocationCoordinate2D locationCoordinate = CLLocationCoordinate2DMake(tipModel.location.latitude, tipModel.location.longitude);

        self.currentLocationCoordinate = locationCoordinate;
        [self showMapPoint];
        [self setCenterPoint];

        self.request.location = [AMapGeoPoint locationWithLatitude:tipModel.location.latitude longitude:tipModel.location.longitude];

        [self kPOIAroundSearchRequest];
        [self.tableView reloadData];

    }
}

//  地图的代理
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.searchTableView) {
        if (@available(iOS 13.0, *)) {
            UIWindow *window = nil;
            for (UIWindowScene *windowScene in [UIApplication sharedApplication].connectedScenes) {

                if (windowScene.activationState == UISceneActivationStateForegroundActive) {

                    window = windowScene.windows.firstObject;

                    break;

                }
            }
            [window endEditing:YES];
        } else {
            [[[UIApplication sharedApplication] keyWindow] endEditing:YES];

        }
    }
}
#pragma mark - UISearchControllerDelegate && UISearchResultsUpdating

//谓词搜索过滤
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    if (searchController.searchBar.text.length == 0) {
        return;
    }
    [self.view addSubview:self.searchTableView];

    //搜索地点
    AMapInputTipsSearchRequest *tips = [[AMapInputTipsSearchRequest alloc] init];
    tips.keywords = searchController.searchBar.text;
    [self.mapSearch AMapInputTipsSearch:tips];

}
#pragma mark - UISearchControllerDelegate代理
- (void)willPresentSearchController:(UISearchController *)searchController{
    self.searchController.searchBar.frame = CGRectMake(0, 0, self.searchController.searchBar.frame.size.width, 44.0);
    self.mapView.frame = CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_WIDTH, 300);
//    self.tableView.frame = CGRectMake(0, 364, SCREEN_WIDTH, SCREEN_HEIGHT - 364);
    NSLog(@"ss---%@",NSStringFromCGRect(self.tableView.frame));

}
- (void)didDismissSearchController:(UISearchController *)searchController{
    self.searchController.searchBar.frame = CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, self.searchController.searchBar.frame.size.width, 44.0);
    self.mapView.frame = CGRectMake(0, 64 + 44, SCREEN_WIDTH, 300);
//    self.tableView.frame = CGRectMake(0, 408, SCREEN_WIDTH, SCREEN_HEIGHT - 408);
    [self.searchTableView removeFromSuperview];
}

- (void)localButtonAction{
    [self locateAction];
}
//  高德地图 隐私政策合规 地图实例化之前 加载
- (void)kGDYSHG{
//地图
//
//    [MAMapView updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
//    [MAMapView updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];

}

@end

